package cn.lyjuan.android.demofive.frame.tpl.demo;

import android.support.v7.widget.RecyclerView;

import com.jimi_wu.ptlrecyclerview.AutoLoad.AutoLoadRecyclerView;
import com.jimi_wu.ptlrecyclerview.PullToLoad.OnLoadListener;
import com.jimi_wu.ptlrecyclerview.PullToRefresh.OnRefreshListener;

import cn.lyjuan.android.demofive.frame.realm.UserModel;
import cn.lyjuan.android.demofive.frame.tpl.AbstractListViewModel;
import io.realm.Realm;
import io.realm.RealmResults;

/**
 * Created by chad on 13/11/2017.
 */

public class RecyclerViewModel extends AbstractListViewModel<UserModel, RealmResults<UserModel>>
{
    protected Realm realm;

    public RecyclerViewModel(Realm realm, RecyclerView listView)
    {
        super(listView);
        this.realm = realm;
        this.adapter = adapter;

        // 设置刷新、加载事件
        ((AutoLoadRecyclerView) listView).setOnRefreshListener(new OnRefreshListener()
        {
            @Override
            public void onStartRefreshing()
            {
                list.clear();
                dataSource.fetchData(true);
            }
        });

        ((AutoLoadRecyclerView) listView).setOnLoadListener(new OnLoadListener()
        {
            @Override
            public void onStartLoading(int i)
            {
                dataSource.fetchData(false);
            }
        });
    }

    @Override
    public void onFetchSucc(RealmResults<UserModel> data, boolean clear)
    {
        list.addAll(data);
//        if (adapter instanceof BaseAdapter)
//            ((BaseAdapter) adapter).notifyDataSetChanged();
//        else if (adapter instanceof RecyclerView.Adapter)
//            ((RecyclerView.Adapter) adapter).notifyDataSetChanged();
//        else
//            Logger.e("unknown adapter type: %s", adapter.getClass().getName());
        if (clear)
            ((AutoLoadRecyclerView) listView).completeRefresh();
        else
            ((AutoLoadRecyclerView) listView).completeLoad(data.size());
    }

    @Override
    public void loadDataSource()
    {
        // 设置数据回调监听
        dataSource = new RealmDataSource(realm);
        dataSource.setFetchDataListener(this);
    }
}
